const router = require("koa-router")();
const multer = require('koa-multer')
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${process.cwd()}/static`)
    },
    filename: function (req, file, cb) {
        let type = file.originalname.split('.')[1]
        cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
    }
})
//加载配置
var upload = multer({
    storage: storage
});
const MembersModel = require("../models/index");//变化

router.get('/',async ctx=>{
    await ctx.render("index")//art-template,koa-art-template//不懂
    // ctx.body = "hello world"            //不懂
    // console.log(ctx.body)   //整个html页面
})
//存储数据
router.post('/doUpload',upload.single('file'), async (ctx, next) => {
    // console.log(ctx.req.body);
    // console.log(ctx.req.file.filename);//不懂
    var {name,age,like} = ctx.req.body;
    var imageUrl = ctx.req.file.filename;
    var data = new MembersModel({name,age,like,imageUrl});//变化
    data.save(err=>{
        if(err){throw err};
    })
    /* ctx.body = {
      filename: ctx.req.file.filename  //返回文件名 //不懂
    }
    console.log(ctx.body); */
})
//展示数据
router.get('/show',async ctx=>{
    // 查询数据
    var data = await MembersModel.find({})//变化
    await ctx.render("show",{arr:data})
    // ctx.body = "hello world"
    // console.log(ctx.body)    //不懂//整个html页面
})

module.exports = router;